﻿using ComponentFactory.Krypton.Toolkit;
using ComponentFactory.Krypton.Docking;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Teigha.DatabaseServices;
using Teigha.Geometry;
using Teigha.GraphicsSystem;
using Teigha.Runtime;
using SRB.Tg.Cad_Bll;
using Teigha.Export_Import;
using System.IO;
using Teigha.GraphicsInterface;
using SRB.Tg.DrawingStandard;
using SRB.Tg.Model;
using SRB.Tg.Operate;
using System.Threading.Tasks;
using System.Threading;
using SRB.Tg.Common;


namespace SRB.Tg.Cad
{
    public partial class TeighaBase : KryptonForm
    {
        #region 防止闪烁
        [DllImport("dwmapi.dll", EntryPoint = "DwmEnableComposition")]
        protected extern static uint Win32DwmEnableComposition(uint uCompositionAction);

        /// <summary>
        /// 防止闪烁
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.ExStyle |= 0x02000000;  // Turn on WS_EX_COMPOSITED
                return cp;
            }
        }
        #endregion

        #region 基本变量
        Teigha.Runtime.Services dd;
        public Graphics graphics;
        public Teigha.GraphicsSystem.LayoutHelperDevice helperDevice;
        public Database database = null;
        ObjectIdCollection selected = new ObjectIdCollection();
        public Point MouseDownPt = new Point();
        public Point MovePoint = new Point();
        public LayoutManager lm;
        public Point3d firstCornerPoint;
        public int bZoomWindow = -1;
        public string DwgPath = "";
       

        //--添加
        Color colorAll= Color.Magenta;
        #endregion

        #region 动作
        public Operations OperModel;
        public List<Entity> selectedClone = new List<Entity>();//临时存放实体
        //public List<Entity> highlightEntity=new List<Entity>();//临时存放高亮选中实体
        RectFram selRect = null;
        public InvokerCommad Invoker;
        #endregion

        private static TeighaBase _instance;
        private static MainForms _parent;
        public static TeighaBase getInstance(MainForms frm)
        {
            if (_instance == null)
            {
                _instance = new TeighaBase();
            }
            else
            {
                //DrawingStandard.Tools.ClearDatabase();
                //_instance.database = HostApplicationServices.WorkingDatabase;
            }
            _parent = frm;
            return _instance;
        }
        public TeighaBase()
        {
            //Control.CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            //parent = (MainForms)this.Parent;
            dd = PublicClass.ServiceD;
            SystemObjects.DynamicLinker.LoadApp("GripPoints", false, false);
            SystemObjects.DynamicLinker.LoadApp("PlotSettingsValidator", false, false);

            this.DoubleBuffered = true;
            HostApplicationServices.Current = new HostAppServ(dd);
            Environment.SetEnvironmentVariable("DDPLOTSTYLEPATHS", ((HostAppServ)HostApplicationServices.Current).FindConfigPath(String.Format("PrinterStyleSheetDir")));
            basepanel.Refresh();
            this.basepanel.Focus();
            this.basepanel.MouseWheel += Basepanel_MouseWheel;
            this.basepanel.Paint += Basepanel_Paint;
            this.basepanel.Resize += Basepanel_Resize;
            this.basepanel.MouseClick += Basepanel_MouseClick;
            this.basepanel.MouseDown += Basepanel_MouseDown;
            this.basepanel.MouseMove += Basepanel_MouseMove;
            this.basepanel.MouseUp += Basepanel_MouseUp;
            this.Paint += Basepanel_Paint;

            Invoker = new InvokerCommad();
            Invoker.ChangeStack += Invoker_ChangeStack;
            
        }
        
        private void TeighaBase_Load(object sender, EventArgs e)
        {
            //file_open_handlerNotBar(@"C:\Users\admin\Desktop\SVN\Interesting\Teigha_Learn_Cad_Bin\OdWriteEx XRef.dwg");
            HotKeysManager.RegisterHotKey(Handle, 100, HotKeysManager.KeyModifiers.Ctrl, Keys.C);
            HotKeysManager.RegisterHotKey(Handle, 101, HotKeysManager.KeyModifiers.Ctrl, Keys.V);
            HotKeysManager.RegisterHotKey(Handle, 102, HotKeysManager.KeyModifiers.Ctrl, Keys.A);
        }
        #region 布局变化委托重新加载
        public delegate void Send_Insert_UC_To_Form_Main();
        public event Send_Insert_UC_To_Form_Main Send_Insert_UC;
        #endregion
        //重写ProcessCmdKey的方法
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, System.Windows.Forms.Keys keyData)
        {
            int WM_KEYDOWN = 256;
            int WM_SYSKEYDOWN = 260;
            if (msg.Msg == WM_KEYDOWN | msg.Msg == WM_SYSKEYDOWN)
            {
                switch (keyData)
                {
                    case Keys.Escape:
                       
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            foreach (ObjectId item in selected)
                            {
                                if (!item.IsNull && !item.IsErased)
                                    using (Entity ent = (Entity)item.GetObject(OpenMode.ForRead))
                                    {
                                        ent.Unhighlight();
                                        selected.Remove(item);
                                    }
                            }

                            OperModel = Operations.None;
                            basepanel.Cursor = Cursors.Default;
                            toolStripButton9.Checked = false;
                            if (helperDevice != null)
                            {
                                helperDevice.Update();
                                Invalidate();
                            }
                        }
                        Send_Insert_UC();
                break;
                }
            }
            return false;
        }
        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            //按快捷键
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case 100:     //按下的是Ctrl+C  选择
                            OperModel = Operations.SelectFrom;
                            basepanel.Cursor = new System.Windows.Forms.Cursor(Properties.Resources.十字光标.GetHicon());
                            break;
                        case 101:     //按下的是Ctrl+V  粘贴
                            OperModel = Operations.CopyEntity;
                            basepanel.Cursor = new System.Windows.Forms.Cursor(Properties.Resources.十字光标.GetHicon());
                            break;
                        case 102:     //按下的是Ctrl+A  自适应
                            zoom_extents_handler();
                            break;
                    }
                    break;
            }
            base.WndProc(ref m);
        }
        #region 基本事件
        private void Basepanel_MouseWheel(object sender, MouseEventArgs e)
        {
            //if (!DragSelected)
            //Send_D_Complete(true);
            //DragSelected = false;
            //if (DragSelected)
            //{
            using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
            {
                // camera position in world coordinates 摄像机在世界坐标中的位置
                Point3d pos = pView.Position;
                // TransformBy() returns a transformed copy TransformBy()返回转换后的副本
                pos = pos.TransformBy(pView.WorldToDeviceMatrix);
                int vx = (int)pos.X;
                int vy = (int)pos.Y;
                vx = e.X - vx;
                vy = e.Y - vy;
                // we move point of view to the mouse location, to create an illusion of scrolling in/out there
                //我们将视图移动到鼠标位置，以创建一个在那里滚动的错觉
                dolly(pView, -vx, -vy);
                //注意，我们实际上忽略了delta值(符号足以说明问题)
                // note that we essentially ignore delta value (sign is enough for illustrative purposes)
                double num = e.Delta > 0 ? 1.0 / 0.9 : 0.9;
                pView.Zoom(num);
                dolly(pView, vx, vy);
                ReceiverViews receive = new ReceiverViews(num, pos, MovePoint, ref helperDevice);
                Invoker.SetCommad(receive);
                Invalidate();
            }
            //}
        }
        bool isInit = false;
        private void Basepanel_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                if (helperDevice != null)
                {
                    try
                    {
                        helperDevice.Update();
                        Invalidate();
                    }
                    catch (System.Exception ex)
                    {
                        return;
                    }
                }
                switch (OperModel)
                {
                    case Operations.None:
                        break;
                    case Operations.Drag:
                        break;
                    case Operations.Roll:
                        break;
                    case Operations.SelectFrom:
                        break;
                    case Operations.MoveEntity:
                        break;
                    case Operations.CopyEntity:
                        break;
                    case Operations.Gyroscope:
                        break;
                    case Operations.RollEntity:
                        break;
                    case Operations.InsertEntity:
                        switch (EntType)
                        {
                            case EntityType.Line:
                                break;
                            case EntityType.Mline:
                                break;
                            case EntityType.None:
                                break;
                            case EntityType.Arc:
                                if (DragSelected)
                                    DrawArcs();
                                break;
                            case EntityType.Circle:
                                if (DragSelected)
                                    DrawCircle();
                                break;
                            default:
                                break;
                        }
                        break;
                    case Operations.PanelDrawPen:
                        DrawPentrack();
                        break;
                    default:
                        break;
                }
            }
            catch(System.Exception ex)
            {

            }
        }

        private void Basepanel_Resize(object sender, EventArgs e)
        {
            resize();
        }

        private void Basepanel_MouseClick(object sender, MouseEventArgs e)
        {
            if (bZoomWindow > -1 && bZoomWindow < 2)
            {
                if (bZoomWindow == 1)
                {
                    bZoomWindow = -1;
                    ZoomWindow(firstCornerPoint, toEyeToWorld(e.X, e.Y));
                }
                if (bZoomWindow == 0)
                {
                    firstCornerPoint = toEyeToWorld(e.X, e.Y);
                    bZoomWindow = 1;
                }
            }
            if (!basepanel.Focused)
                basepanel.Focus();
        }

        private void Basepanel_MouseDown(object sender, MouseEventArgs e)
        {
            MouseDownPt = new Point(e.X, e.Y);
            if (e.Button == System.Windows.Forms.MouseButtons.Middle)
                Send_D_Complete(true);
            switch (OperModel)
            {
                case Operations.None:
                    #region 获取当前鼠标选中点
                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                    {
                        ObjectIdCollection selectNEw = new ObjectIdCollection();
                        pView.Select(new Point2dCollection(new Point2d[] { new Point2d(MouseDownPt.X + 5, MouseDownPt.Y + 5), new Point2d(MouseDownPt.X - 5, MouseDownPt.Y - 5) }),
                          new SRnew(selectNEw, database.CurrentSpaceId), Teigha.GraphicsSystem.SelectionMode.Crossing);

                        if (selectNEw != null && selectNEw.Count > 0)
                        {
                            foreach (ObjectId item in selected)
                            {
                                try
                                {
                                    if (!item.IsNull && !item.IsErased)
                                        using (Entity ent = (Entity)item.GetObject(OpenMode.ForRead))
                                        {
                                            ent.Unhighlight();
                                        }
                                }
                                catch { }
                            }

                            if (IsBool && EditEnt != null)
                            {
                                EditEnt.setEditEntitys(selectNEw, ref database, ref helperDevice);
                            }
                            //两次选择相同项
                            if (IsSelecttheSame(selected, selectNEw))
                            {
                                #region 移动实体
                                selectedClone = new List<Entity>();
                                foreach (ObjectId item in selectNEw)
                                {
                                    if (!item.IsErased)
                                    {
                                        Entity ent = (Entity)item.GetObject(OpenMode.ForRead, false, false);
                                        Entity entClone = (Entity)ent.Clone();
                                        entClone.Highlight();
                                        pView.Add(entClone);
                                        selectedClone.Add(entClone);
                                    }
                                }
                                this.Cursor = Cursors.SizeAll;
                                OperModel = Operations.MoveEntity;

                                #endregion
                            }
                            selected = selectNEw;
                        
                            foreach (ObjectId item in selected)
                            {
                                if (!item.IsNull && !item.IsErased)
                                    using (Entity ent = (Entity)item.GetObject(OpenMode.ForRead))
                                    {
                                        ent.Highlight();
                                    }
                            }
                        }
                        //gripManager.updateSelection(selected);
                        helperDevice.Invalidate();
                        Invalidate();
                    }
                    #endregion
                    CopyEntitylist_view(MouseDownPt);
                    break;
                case Operations.Drag:
                    #region 拖拽
                    DragSelected = true;
                    basepanel.Cursor = new System.Windows.Forms.Cursor(Properties.Resources.拖拽32白色2.GetHicon());
                    
                    #endregion
                    break;
                case Operations.Roll:
                    break;
                case Operations.Gyroscope:
                    break;
                case Operations.RollEntity:
                    break;
                case Operations.CopyEntity:
                    //if (e.Button == MouseButtons.Left)
                    //{
                        //CopyEntitylist_view(MouseDownPt);
                    //}
                    break;
                case Operations.InsertEntity:
                    if (e.Button == MouseButtons.Left)
                    {
                        InsertEntityDowm(e.X, e.Y);
                        DragSelected = true;
                    }
                    break;
                case Operations.PanelDrawPen:
                    List<Point> ListNew = new List<Point>();
                    ListNew.Add(new Point(e.X - 16, e.Y + 16));
                    ListDrwaPen.Add(ListNew);
                    DragSelected = true;
                    break;
                case Operations.SelectFrom:
                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                    {
                        selRect = new RectFram(toEyeToWorld(e.X, e.Y));
                        pView.Add(selRect);
                    }
                    CopyEntitylist_view(MouseDownPt);
                    break;
                default:
                    break;
            }
        }

        private void Basepanel_MouseMove(object sender, MouseEventArgs e)
        {
            MovePoint = new Point(e.X, e.Y);
            if (database != null && helperDevice != null)
            {
                Point3d Point = toEyeToWorld(e.X, e.Y);
                toolCoordinates.Text = "(X: " + Math.Round(Point.X, 5) + ", Y: " + Math.Round(Point.Y, 5) + ", Z:" + Math.Round(Point.Z, 5) + ")";
            }

            switch (OperModel)
            {
                case Operations.None:
                    break;
                case Operations.Drag:
                    if (DragSelected)
                        Viewer_UDLR(new Point(e.X, e.Y));
                    break;
                case Operations.Roll:
                    break;
                case Operations.MoveEntity:
                        MoverEntitylist_view(new Point(e.X, e.Y));
                    break;
                case Operations.CopyEntity:
                    //CopyEntitylist_view(new Point(e.X, e.Y));
                    break;
                case Operations.Gyroscope:
                    break;
                case Operations.RollEntity:
                    break;
                case Operations.InsertEntity:
                        InsertEntityMove(e.X, e.Y);
                    break;
                case Operations.PanelDrawPen:
                    if (DragSelected)
                    {
                        if (ListDrwaPen.Count > 0)
                        {
                            ListDrwaPen[ListDrwaPen.Count - 1].Add(new Point(e.X - 16, e.Y + 16));
                            DrawPentrack();
                        }
                    }
                    break;
                case Operations.SelectFrom:
                    if(selRect!=null)
                        selRect.setValue(toEyeToWorld(e.X, e.Y));
                    if (helperDevice != null)
                    {
                        helperDevice.Update();
                        Invalidate();
                    }
                    break;
                default:
                    break;
            }
           
        }
        #region 布局变化委托重新加载
        public delegate void Send_D_Complete_To_Form_Main(bool isCheck);
        public event Send_D_Complete_To_Form_Main Send_D_Complete;
        #endregion
        private void Basepanel_MouseUp(object sender, MouseEventArgs e)
        {
            switch (OperModel)
            {
                case Operations.None:
                    if (DragSelected)
                        DragSelected = false;
                    break;
                case Operations.Drag:
                    DragSelected = false;
                    basepanel.Cursor = new System.Windows.Forms.Cursor(Properties.Resources.拖拽32白色.GetHicon());
                    Send_D_Complete(false);
                    break;
                case Operations.Roll:
                    break;
                case Operations.MoveEntity:
                    Podowns = new Point(0, 0);
                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                    {
                        foreach (Entity item in selectedClone)
                        {
                            if (!item.IsErased)
                            {
                                pView.Erase(item);
                            }
                        }
                    }
                    MoverEntity_view(new Point(e.X, e.Y));
                    this.Cursor = Cursors.Default;
                    OperModel = Operations.None;
                    break;
                case Operations.CopyEntity:
                    Podowns = new Point(0, 0);
                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                    {
                        foreach (Entity item in selectedClone)
                        {
                            if (!item.IsErased)
                            {
                                pView.Erase(item);
                            }
                        }
                    }
                    CopyEntity_view(new Point(e.X, e.Y));
                    this.Cursor = Cursors.Default;
                    OperModel = Operations.None;
                    break;
                case Operations.Gyroscope:
                    break;
                case Operations.RollEntity:
                    break;
                case Operations.InsertEntity:
                    InsertMouseUp(e);
                    break;
                case Operations.PanelDrawPen:
                    DragSelected = false;
                    break;
                case Operations.SelectFrom:
                    if (selRect != null)
                    {
                        #region 批量
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            ObjectIdCollection objection = new ObjectIdCollection();
                            pView.Select(new Point2dCollection(new Point2d[] { new Point2d(MouseDownPt.X, MouseDownPt.Y), new Point2d(e.X, e.Y) }),
                              new SRnew(objection, database.CurrentSpaceId), Teigha.GraphicsSystem.SelectionMode.Crossing);
                            foreach (ObjectId item in selected)
                            {
                                if (!item.IsNull && !item.IsErased)
                                    using (Entity ent = (Entity)item.GetObject(OpenMode.ForRead))
                                    {
                                        ent.Unhighlight();
                                    }
                            }
                            selected = objection;
                            pView.Erase(selRect);
                            selRect = null;
                            foreach (ObjectId item in selected)
                            {
                                if (!item.IsNull && !item.IsErased)
                                    using (Entity ent = (Entity)item.GetObject(OpenMode.ForRead))
                                    {
                                        ent.Highlight();
                                    }
                            }
                            
                        }
                        #endregion

                        OperModel = Operations.None;
                        basepanel.Cursor = Cursors.Default;
                        toolStripButton9.Checked = false;
                        if (helperDevice != null)
                        {
                            helperDevice.Update();
                            Invalidate();
                        }
                    }
                    break;
                default:
                    break;
            }
           
        }
        #endregion

        #region 私有方法
        /// <summary>
        /// 移动视图
        /// </summary>
        /// <param name="PoMove"></param>
        private void Viewer_UDLR(Point PoMove)
        {
            double dx = -(PoMove.X - MouseDownPt.X);
            double dy = -(PoMove.Y - MouseDownPt.Y);
            MouseDownPt = new Point(PoMove.X, PoMove.Y);
            using (DBObject pVpObj = active_viewport_id(database).GetObject(OpenMode.ForWrite))
            {
                AbstractViewportData pAVD = new AbstractViewportData(pVpObj);
                Teigha.GraphicsSystem.View pView = pAVD.GsView;

                Vector3d vec = new Vector3d(dx, dy, 0.0);
                vec = vec.TransformBy((pView.ScreenMatrix * pView.ProjectionMatrix).Inverse());
                pView.Dolly(vec);
                pAVD.SetView(pView);
                pAVD.Dispose();
                pVpObj.Dispose();
                Invalidate();
            }

        }

        private void ZoomWindow(Point3d pt1, Point3d pt2)
        {
            using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
            {
                using (AbstractViewPE pVpPE = new AbstractViewPE(pView))
                {
                    pt1 = pt1.TransformBy(pVpPE.WorldToEye);
                    pt2 = pt2.TransformBy(pVpPE.WorldToEye);
                    Vector3d eyeVec = pt2 - pt1;

                    if (((eyeVec.X < -1E-10) || (eyeVec.X > 1E-10)) && ((eyeVec.Y < -1E-10) || (eyeVec.Y > 1E-10)))
                    {
                        Point3d newPos = pt1 + eyeVec / 2.0;
                        pView.Dolly(newPos.GetAsVector());
                        double wf = pView.FieldWidth / Math.Abs(eyeVec.X);
                        double hf = pView.FieldHeight / Math.Abs(eyeVec.Y);
                        pView.Zoom(wf < hf ? wf : hf);
                        Invalidate();
                    }
                }
            }
        }

        private ObjectId active_viewport_id(Database database)
        {

            if (database.TileMode)
            {
                return database.CurrentViewportTableRecordId;
            }
            else
            {
                using (BlockTableRecord paperBTR = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForRead))
                {
                    Layout l = (Layout)paperBTR.LayoutId.GetObject(OpenMode.ForRead);
                    return l.CurrentViewportId;
                }
            }

        }

        private void dolly(Teigha.GraphicsSystem.View pView, int x, int y)
        {
            Vector3d vec = new Vector3d(-x, -y, 0.0);
            vec = vec.TransformBy((pView.ScreenMatrix * pView.ProjectionMatrix).Inverse());
            pView.Dolly(vec);
        }

        private void resize()
        {
            try
            {
                if (helperDevice != null)
                {
                    Rectangle r = basepanel.Bounds;
                    r.Offset(-basepanel.Location.X, -basepanel.Location.Y);
                    // HDC assigned to the device corresponds to the whole client area of the panel
                    helperDevice.OnSize(r);
                    Invalidate();
                }
            }
            catch
            {

            }
        }

        public Point3d toEyeToWorld(int x, int y)
        {
            try
            {
                using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                {
                    Point3d wcsPt = new Point3d(x, y, 0.0);
                    wcsPt = wcsPt.TransformBy((pView.ScreenMatrix * pView.ProjectionMatrix).Inverse());
                    wcsPt = new Point3d(wcsPt.X, wcsPt.Y, 0.0);
                    using (AbstractViewPE pVpPE = new AbstractViewPE(pView))
                    {
                        return wcsPt.TransformBy(pVpPE.EyeToWorld);
                    }
                }
            }
            catch (System.Exception)
            {
            }
            return toEyeToWorld(x, y);
        }

        public void reinitGraphDevice(object sender, Teigha.DatabaseServices.LayoutEventArgs e)
        {
                helperDevice.Dispose();
                graphics.Dispose();
                initializeGraphics(); 
        }

        private  void initializeGraphics()
        {
            try
            {
                graphics = Graphics.FromHwnd(basepanel.Handle);
                // load some predefined rendering module (may be also "WinDirectX" or "WinOpenGL")
                using (GsModule gsModule = (GsModule)SystemObjects.DynamicLinker.LoadModule("WinGDI.txv", false, true))
                {
                    // create graphics device
                    using (Teigha.GraphicsSystem.Device graphichsDevice = gsModule.CreateDevice())
                    {
                        // setup device properties
                        using (Dictionary props = graphichsDevice.Properties)
                        {
                            if (props.Contains("WindowHWND")) // Check if property is supported
                                props.AtPut("WindowHWND", new RxVariant((Int32)basepanel.Handle)); // hWnd necessary for DirectX device
                            if (props.Contains("WindowHDC")) // Check if property is supported
                                props.AtPut("WindowHDC", new RxVariant(graphics.GetHdc())); // hWindowDC necessary for Bitmap device
                            if (props.Contains("DoubleBufferEnabled")) // Check if property is supported
                                props.AtPut("DoubleBufferEnabled", new RxVariant(true));
                            if (props.Contains("EnableSoftwareHLR")) // Check if property is supported
                                props.AtPut("EnableSoftwareHLR", new RxVariant(true));
                            if (props.Contains("DiscardBackFaces")) // Check if property is supported
                                props.AtPut("DiscardBackFaces", new RxVariant(true));
                        }
                        // setup paperspace viewports or tiles
                        Teigha.GraphicsInterface.ContextForDbDatabase ctx = new Teigha.GraphicsInterface.ContextForDbDatabase(database);
                        ctx.UseGsModel = true;
                    
                        helperDevice = LayoutHelperDevice.SetupActiveLayoutViews(graphichsDevice, ctx);
                     
                        //Aux.preparePlotstyles(database, ctx);
                        //helperDevice.ActiveView.Mode = Teigha.GraphicsSystem.RenderMode.HiddenLine;
                    }
                }
               
                // set palette
                helperDevice.SetLogicalPalette(Device.DarkPalette);
                // set output extents
                resize();


                helperDevice.Model.Invalidate(InvalidationHint.kInvalidateAll);
        
            }
            catch (System.Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }
        }
        bool isZoom = false;
        void zoom_extents(Teigha.GraphicsSystem.View pView, DBObject pVpObj)
        {
            try
            {
                if (!isZoom)
                {
                    isZoom = true;
                    if (pView == null)
                        return;
                    // here protocol extension is used again, that provides some helpful functions
                    //这里再次使用了协议扩展，提供了一些有用的功能

                    using (AbstractViewPE pVpPE = new AbstractViewPE(pView))
                    {
                        //pView.Update();
                        BoundBlock3d bbox = new BoundBlock3d();
                        bool bBboxValid = pVpPE.GetViewExtents(bbox);

                        // paper space overall view 纸张空间全景
                        if (pVpObj is Teigha.DatabaseServices.Viewport && ((Teigha.DatabaseServices.Viewport)pVpObj).Number == 1)
                        {
                            if (!bBboxValid || !(bbox.GetMinimumPoint().X < bbox.GetMaximumPoint().X && bbox.GetMinimumPoint().Y < bbox.GetMaximumPoint().Y))
                            {
                                bBboxValid = get_layout_extents(database, pView, ref bbox);
                            }
                        }

                        else if (!bBboxValid) // model space viewport 模型空间窗口
                        {
                            bBboxValid = get_layout_extents(database, pView, ref bbox);
                        }

                        if (!bBboxValid)
                        {
                            // set to somewhat reasonable (e.g. paper size) 设置为比较合理(例如纸张大小)
                            if (database.Measurement == MeasurementValue.Metric)
                            {
                                bbox.Set(Point3d.Origin, new Point3d(297.0, 210.0, 0.0)); // set to papersize ISO A4 (portrait)
                            }
                            else
                            {
                                bbox.Set(Point3d.Origin, new Point3d(11.0, 8.5, 0.0)); // ANSI A (8.50 x 11.00) (landscape)
                            }
                            bbox.TransformBy(pView.ViewingMatrix);
                        }

                        pVpPE.ZoomExtents(bbox);
                    }
                }
            }
            catch
            {

            }
            finally
            {
                isZoom = false;
            }
        }

        bool get_layout_extents(Database db, Teigha.GraphicsSystem.View pView, ref BoundBlock3d bbox)
        {
            BlockTable bt = (BlockTable)db.BlockTableId.GetObject(OpenMode.ForRead);
            BlockTableRecord pSpace = (BlockTableRecord)bt[BlockTableRecord.PaperSpace].GetObject(OpenMode.ForRead);
            Layout pLayout = (Layout)pSpace.LayoutId.GetObject(OpenMode.ForRead);
            Extents3d ext = new Extents3d();
            if (pLayout.GetViewports().Count > 0)
            {
                bool bOverall = true;
                foreach (ObjectId id in pLayout.GetViewports())
                {
                    if (bOverall)
                    {
                        bOverall = false;
                        continue;
                    }

                    Teigha.DatabaseServices.Viewport pVp = (Teigha.DatabaseServices.Viewport)id.GetObject(OpenMode.ForRead);
                }
                ext.TransformBy(pView.ViewingMatrix);
                bbox.Set(ext.MinPoint, ext.MaxPoint);
            }
            else
            {
                ext = pLayout.Extents;
            }
            bbox.Set(ext.MinPoint, ext.MaxPoint);
            return ext.MinPoint != ext.MaxPoint;
        }

        public bool IsSelecttheSame(ObjectIdCollection Objitem1, ObjectIdCollection Objitem2)
        {
            if (Objitem1.Count == Objitem2.Count)
            {
                for (int i = 0; i < Objitem1.Count; i++)
                {
                    if (Objitem1[i] != Objitem2[i])
                        return false;
                }
                return true;
            }
            return false;
        }

        public void DWF_export(Database database, Teigha.GraphicsSystem.LayoutHelperDevice helperDevice)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.DefaultExt = "dwf";
            sfd.Title = "Export To Dwf";
            sfd.Filter = String.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}",
              "Binary DWF (Desgin Web Format) v6.0 (*.dwf)|*.dwf",
              "Zipped Ascii Encoded 2D Stream DWF (Design Web Format) v6.0 (*.dwf)|*.dwf",
              "Compressed DWF (Design Web Format) v5.5 (*.dwf)|*.dwf",
              "Binary DWF (Design Web Format) v5.5 (*.dwf)|*.dwf",
              "Ascii DWF (Design Web Format) v5.5 (*.dwf)|*.dwf",
              "Compressed DWF (Design Web Format) v4.2 (*.dwf)|*.dwf",
              "Binary DWF (Design Web Format) v4.2 (*.dwf)|*.dwf",
              "Ascii DWF (Design Web Format) v4.2 (*.dwf)|*.dwf");
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                String strFileName = sfd.FileName;
                using (mDwfExportParams param = new mDwfExportParams())
                {
                    param.Database = database;
                    param.FileName = strFileName;
                    param.BackgroundColor = helperDevice.BackgroundColor;
                    param.InkedArea = false;
                    param.ColorMapOptimize = false;
                    param.ExportInvisibleText = true;
                    DwfPageDataCollection pageDataColl = new DwfPageDataCollection();
                    DWFPageData pageData;
                    switch (sfd.FilterIndex)
                    {
                        case 1:
                            param.Format = DwfFormat.UNCOMPRESSED_BINARY;
                            param.Version = DwfVersion.Dwf_v60;

                            pageData = new DWFPageData();
                            pageData.Layout = LayoutManager.Current.CurrentLayout;
                            pageDataColl.Add(pageData);
                            param.PageData = pageDataColl;
                            break;
                        case 2:
                            param.Format = DwfFormat.ASCII;
                            param.Version = DwfVersion.Dwf_v60;

                            pageData = new DWFPageData();
                            pageData.Layout = LayoutManager.Current.CurrentLayout;
                            pageDataColl.Add(pageData);
                            param.PageData = pageDataColl;
                            break;
                        case 3:
                            param.Format = DwfFormat.COMPRESSED_BINARY;
                            param.Version = DwfVersion.Dwf_v55;
                            break;
                        case 4:
                            param.Format = DwfFormat.UNCOMPRESSED_BINARY;
                            param.Version = DwfVersion.Dwf_v55;
                            break;
                        case 5:
                            param.Format = DwfFormat.ASCII;
                            param.Version = DwfVersion.Dwf_v55;
                            break;
                        case 6:
                            param.Format = DwfFormat.COMPRESSED_BINARY;
                            param.Version = DwfVersion.Dwf_v42;
                            break;
                        case 7:
                            param.Format = DwfFormat.UNCOMPRESSED_BINARY;
                            param.Version = DwfVersion.Dwf_v42;
                            break;
                        case 8:
                            param.Format = DwfFormat.ASCII;
                            param.Version = DwfVersion.Dwf_v42;
                            break;
                        default:
                            return;
                    }
                    Export_Import.ExportDwf(param);
                }
            }
        }

        #endregion

        #region 公共方法
        bool islock = false;
        /// <summary>
        /// 初始化Dwg并显示 无进度条
        /// </summary>
        /// <param name="Paths"></param>
        public void file_open_handlerNotBar(object Paths)
        {
          
            try
            {
                if (!islock)
                {
                    islock = true;
                    DwgPath = Paths.ToString();
                    if (System.IO.File.Exists(Paths.ToString()))
                    {
                        if (lm != null)
                        {
                            lm.LayoutSwitched -= new Teigha.DatabaseServices.LayoutEventHandler(reinitGraphDevice);
                            HostApplicationServices.WorkingDatabase = null;
                            lm = null;
                            //reinitGraphDevice(null, null);
                        }
                        bool bLoaded = true;
                        database = new Database(false, false);
                        if (System.IO.Path.GetExtension(Paths.ToString()).ToLower() == ".dwg"
                         || System.IO.Path.GetExtension(Paths.ToString()).ToLower() == ".tmp")
                        {
                            try
                            {
                                database.ReadDwgFile(Paths.ToString(), FileOpenMode.OpenForReadAndAllShare, false, "");

                            }
                            catch (System.Exception ex)
                            {
                                KryptonMessageBox.Show("打开失败" + Environment.NewLine + "错误原因：" + ex.Message);
                                //.Show(ex.Message);
                                database.ReadDwgFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"Template\dwgModel.dwg", FileOpenMode.OpenForReadAndAllShare, false, "");
                                //bLoaded = false;
                            }
                        }
                        else if (System.IO.Path.GetExtension(Paths.ToString()).ToLower() == ".dxf")
                        {
                            try
                            {
                                database.DxfIn(Paths.ToString(), "");
                            }
                            catch (System.Exception ex)
                            {
                                KryptonMessageBox.Show("打开失败" + Environment.NewLine + "错误原因：" + ex.Message);
                                database.ReadDwgFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + @"Template\dwgModel.dwg", FileOpenMode.OpenForReadAndAllShare, false, "");
                                //MessageBox.Show(ex.Message);
                                //bLoaded = false;
                            }
                        }
                        if (bLoaded)
                        {
                            //设置当前活动数据库
                            HostApplicationServices.WorkingDatabase = database;
                            lm = LayoutManager.Current;

                           
                            String str = HostApplicationServices.Current.FontMapFileName;
                            this.Text = String.Format("[{0}]", System.IO.Path.GetFileName(Paths.ToString()));
                            this.Tag = Paths;
                            lm.LayoutSwitched += new Teigha.DatabaseServices.LayoutEventHandler(reinitGraphDevice);

                            initializeGraphics();

                            this.Invalidate();
                            this.Focus();
                        }
                    }
                }
            }
            catch(System.Exception ex)
            {

            }
            finally
            {
                islock = false;
            }
        }


        #endregion

        #region 览图事件

        /// <summary>
        /// Dwg 自适应内容
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void zoom_extents_handler()
        {
            using (DBObject pVpObj = active_viewport_id(database).GetObject(OpenMode.ForWrite))
            {
                // using protocol extensions we handle PS and MS viewports in the same manner 使用协议扩展，我们以相同的方式处理PS和MS视图
                AbstractViewportData pAVD = new AbstractViewportData(pVpObj);
                Teigha.GraphicsSystem.View pView = pAVD.GsView;
                if (pView != null)
                {
                    // do actual zooming - change GS view 实际缩放-改变GS视图
                    zoom_extents(pView, pVpObj);
                    // save changes to database 保存对数据库的更改
                    pAVD.SetView(pView);
                    pAVD.Dispose();
                    pVpObj.Dispose();
                    Invalidate();
                }
            }
        }

        /// <summary>
        /// 缩放
        /// </summary>
        /// <param name="num"></param>
        public void Set_zoom(double num)
        {
            try
            {
                using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                {  // camera position in world coordinates
                    Point3d pos = pView.Position;
                    // TransformBy() returns a transformed copy
                    pos = pos.TransformBy(pView.WorldToDeviceMatrix);
                    int vx = (int)pos.X;
                    int vy = (int)pos.Y;
                    vx = MovePoint.X - vx;
                    vy = MovePoint.Y - vy;
                    // we move point of view to the mouse location, to create an illusion of scrolling in/out there
                    dolly(pView, -vx, -vy);
                    pView.Zoom(num);
                    dolly(pView, vx, vy);
                    //
                    ReceiverViews receive = new ReceiverViews(num, pos, MovePoint, ref helperDevice);
                    //ReceiverView Receive = new ReceiverView(new Point(MovePoint.X, MovePoint.Y), new Point((int)pos.X, (int)pos.Y), num, ref database, ref helperDevice);
                    Invoker.SetCommad(receive);

                    Invalidate();
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        #region 图层
        /// <summary>
        /// 关闭选中
        /// </summary>
        public void LayerHidePitchOn()
        {
            using (var trans = database.TransactionManager.StartTransaction())
            {
                foreach (ObjectId item in selected)
                {
                    if (!item.IsNull && !item.IsErased)
                    {
                        Entity ent = item.GetObject(OpenMode.ForRead) as Entity;
                        LayerTableRecord LayerEnt = trans.GetObject(ent.LayerId, OpenMode.ForWrite) as LayerTableRecord;
                        LayerEnt.IsOff = true;
                    }
                }
                trans.Commit();
            }
            helperDevice.Invalidate();
            Invalidate();
        }

        /// <summary>
        /// 关闭除选中之外的图层
        /// </summary>
        public void LayerHideExceptPitchOn()
        {
            using (var trans = database.TransactionManager.StartTransaction())
            {
                List<ObjectId> PutchonObj = new List<ObjectId>();
                foreach (ObjectId item in selected)
                {
                    if (!item.IsNull && !item.IsErased)
                    {
                        Entity ent = item.GetObject(OpenMode.ForWrite) as Entity;
                        PutchonObj.Add(ent.LayerId);
                    }
                }
                LayerTable LatTab = trans.GetObject(database.LayerTableId, OpenMode.ForWrite) as LayerTable;
                foreach (ObjectId item in LatTab)
                {
                    if (PutchonObj.Where(s1 => { return s1 == item; }).ToList().Count() == 0)
                    {
                        LayerTableRecord LayerEnt = trans.GetObject(item, OpenMode.ForWrite) as LayerTableRecord;
                        LayerEnt.IsOff = true;
                    }
                }

                trans.Commit();
            }
            helperDevice.Invalidate();
            Invalidate();

        }

        /// <summary>
        /// 打开所有图层
        /// </summary>
        public void LayerShowAll()
        {
            using (var trans = database.TransactionManager.StartTransaction())
            {

                LayerTable LatTab = trans.GetObject(database.LayerTableId, OpenMode.ForWrite) as LayerTable;
                foreach (ObjectId item in LatTab)
                {
                    LayerTableRecord LayerEnt = trans.GetObject(item, OpenMode.ForWrite) as LayerTableRecord;
                    LayerEnt.IsOff = false;
                }
                trans.Commit();
            }
            helperDevice.Invalidate();
            Invalidate();
        }

        #endregion
        
        #region 移动实体
        /// <summary>
        /// 中间过渡坐标点
        /// </summary>
        Point Podowns = new Point();
        private void MoverEntitylist_view(Point PoMove)
        {
            Point3d Podown1 = new Point3d();
            Point3d Pomove1 = new Point3d();
            double dx = 0;
            double dy = 0;
            if (Podowns == new Point(0, 0))
            {
                Podown1 = toEyeToWorld(MouseDownPt.X, MouseDownPt.Y);
                Pomove1 = toEyeToWorld(PoMove.X, PoMove.Y);
                dx = Pomove1.X - Podown1.X;
                dy = Pomove1.Y - Podown1.Y;
                Podowns = PoMove;
            }
            else
            {
                Podown1 = toEyeToWorld(Podowns.X, Podowns.Y);
                Pomove1 = toEyeToWorld(PoMove.X, PoMove.Y);
                dx = Pomove1.X - Podown1.X;
                dy = Pomove1.Y - Podown1.Y;
                Podowns = PoMove;
            }
            //防止重复移动
            List<Entity> Listitem = new List<Entity>();
            using (var trans = database.TransactionManager.StartTransaction())
            {
                foreach (Entity item in selectedClone)
                {
                    if (Listitem.FindIndex(s1 => s1 == item) == -1)
                    {
                        Listitem.Add(item);
                        //移动
                        Point3d Pointnew = new Point3d(dx, dy, 0);
                        Matrix3d mat = Matrix3d.Displacement(Pointnew.GetAsVector());
                        item.TransformBy(mat);
                    }
                }
                trans.Commit();
            }
            Listitem.Clear();
            if (helperDevice != null)
                helperDevice.Update();
            helperDevice.Invalidate();
            Invalidate();
        }

        Point Pointdowns = new Point();
        private void CopyEntitylist_view(Point PoMove)
        {
            Pointdowns = PoMove;           
        }

        /// <summary>
        /// 移动实体
        /// </summary>
        /// <param name="PoMove"></param>
        private void CopyEntity_view(Point PoMove)
        {
            Point3d Podown1 = toEyeToWorld(Pointdowns.X, Pointdowns.Y);
            Point3d Pomove1 = toEyeToWorld(PoMove.X, PoMove.Y);
            //double dx = Pomove1.X - Podown1.X;
            //double dy = Pomove1.Y - Podown1.Y;

            //if (dx == 0 && dy == 0)
            //    return;

            //防止重复移动
            List<ObjectId> Listitem = new List<ObjectId>();

            List<Entity> entold = new List<Entity>();
            List<Entity> newold = new List<Entity>();
            ObjectIdCollection oldids = new ObjectIdCollection();
            ObjectIdCollection newids = new ObjectIdCollection();
            using (var trans = database.TransactionManager.StartTransaction())
            {
                foreach (ObjectId item in selected)
                {
                    if (Listitem.FindIndex(s1 => s1 == item) == -1)
                    {
                        Listitem.Add(item);
                        if (!item.IsErased && item.IsValid)
                        {
                            using (Entity Ent = item.GetObject(OpenMode.ForWrite) as Entity)
                            {
                                Entity oldent = (Entity)Ent.Clone();
                                oldids.Add(Ent.Id);
                                ObjectId newid = new ObjectId();
                              
                                entold.Add(oldent);
                                //Objids.Add(item);
                                //OldEnts.Add((Entity)Ent.Clone());
                                //移动
                                //Point3d Pointnew = new Point3d(dx, dy, 0);
                                //Matrix3d mat = Matrix3d.Displacement(Pointnew.GetAsVector());
                                //Ent.TransformBy(mat);
                                newid= Ent.Copy(Pomove1, Podown1);
                                newids.Add(newid);
                                Entity newent = newid.GetObject(OpenMode.ForWrite) as Entity;
             
                                newold.Add(newent);


                            }
                        }
                    }
                }
                if (selected.Count > 0)
                {
                    ReceiverSelection entCommand = new ReceiverSelection(oldids, newids, entold, newold, ref database, ref helperDevice);
                    Invoker.SetCommad(entCommand);
                }
                trans.Commit();
            }

            Listitem.Clear();
            if (helperDevice != null)
                helperDevice.Update();
            helperDevice.Invalidate();
            Invalidate();

            //foreach (ObjectId item in Objids)
            //{
            //    NewEnts.Add((Entity)item.GetObject(OpenMode.ForRead, false, false).Clone());
            //}

            //ReceiverSelection Eecesect = new ReceiverSelection(Objids, OldEnts, NewEnts, ref database, ref helperDevice);
            //InvokerCom.SetCommad(Eecesect);
        }
        /// <summary>
        /// 画实体移动
        /// </summary>
        public void MoveEntity()
        {
            try
            {
                using (Graphics g = basepanel.CreateGraphics())
                {
                    //设置高质量插值法    
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    //设置高质量,低速度呈现平滑程度    
                    //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
                    //消除锯齿  
                    //g.SmoothingMode = SmoothingMode.AntiAlias;
                    g.PageUnit = GraphicsUnit.Pixel;


                    Pen penMultiLine = new Pen(Color.White, 2); //在每个点上画延长线用的
                                                                //penMultiLine.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
                                                                //penMultiLine.DashPattern = new float[] { 5, 5 };
                    penMultiLine.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
                    g.DrawImage(imageList1.Images[2], new PointF(MouseDownPt.X - 16, MouseDownPt.Y - 16));
                    g.DrawLine(penMultiLine, MouseDownPt, MovePoint); //显示中心点坐标

                    g.Save();
                }
            }
            catch { }
        }

        /// <summary>
        /// 移动实体
        /// </summary>
        /// <param name="PoMove"></param>
        private void MoverEntity_view(Point PoMove)
        {
            Point3d Podown1 = toEyeToWorld(MouseDownPt.X, MouseDownPt.Y);
            Point3d Pomove1 = toEyeToWorld(PoMove.X, PoMove.Y);
            double dx = Pomove1.X - Podown1.X;
            double dy = Pomove1.Y - Podown1.Y;

            if (dx == 0 && dy == 0)
                return;

            //防止重复移动
            List<ObjectId> Listitem = new List<ObjectId>();

            List<Entity> entold = new List<Entity>();
            List<Entity> newold = new List<Entity>();
            ObjectIdCollection oldids = new ObjectIdCollection();
            ObjectIdCollection newids = new ObjectIdCollection();
            using (var trans = database.TransactionManager.StartTransaction())
            {
                foreach (ObjectId item in selected)
                {
                    if (Listitem.FindIndex(s1 => s1 == item) == -1)
                    {
                        Listitem.Add(item);
                        if (!item.IsErased && item.IsValid)
                        {
                            using (Entity Ent = item.GetObject(OpenMode.ForWrite) as Entity)
                            {
                                Entity oldent = (Entity)Ent.Clone();
                                oldids.Add(Ent.Id);
                                newids.Add(Ent.Id);
                                entold.Add(oldent);
                                //Objids.Add(item);
                                //OldEnts.Add((Entity)Ent.Clone());
                                //移动
                                Point3d Pointnew = new Point3d(dx, dy, 0);
                                Matrix3d mat = Matrix3d.Displacement(Pointnew.GetAsVector());
                                Ent.TransformBy(mat);
                                Entity newent = (Entity)Ent.Clone();
                                newold.Add(newent);

                               
                            }
                        }
                    }
                }
                if (selected.Count > 0)
                {
                    ReceiverSelection entCommand = new ReceiverSelection(oldids, newids, entold, newold, ref database, ref helperDevice);
                    Invoker.SetCommad(entCommand);
                }
                trans.Commit();
            }

            Listitem.Clear();
            if (helperDevice != null)
                helperDevice.Update();
            helperDevice.Invalidate();
            Invalidate();

            //foreach (ObjectId item in Objids)
            //{
            //    NewEnts.Add((Entity)item.GetObject(OpenMode.ForRead, false, false).Clone());
            //}

            //ReceiverSelection Eecesect = new ReceiverSelection(Objids, OldEnts, NewEnts, ref database, ref helperDevice);
            //InvokerCom.SetCommad(Eecesect);
        }
        #endregion

        #region 功能栏事件
        //另存为
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (database != null)
            {
                if (DialogResult.OK == saveAsFileDialog.ShowDialog(this))
                {
                    database.SaveAs(saveAsFileDialog.FileName, DwgVersion.AC1021);


                    //try
                    //{
                    //    string filePath = "";
                    //    string file = saveAsFileDialog.FileName;
                    //    //打开数据库(dwg⽂件)
                    //    using (Database db = new Database(false, false))//不加参数会出错
                    //    {

                    //        db.ReadDwgFile(file, FileOpenMode.OpenForReadAndAllShare, false, "");
                    //        LayoutTools.PlotDrawingByTK(db, "图纸", "ISO_full_bleed_A3_(420.00_x_297.00_MM)", "monochrome.ctb", "DWG To PDF.pc3", file, out filePath);
                    //    }
                    //}
                    //catch (Teigha.Runtime.Exception ex)
                    //{

                    //}

                }
            }
        }


        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (database != null)
            {
                database.SaveAs(DwgPath, DwgVersion.AC1021);
                LayoutManager LM = LayoutManager.Current;
                LM.CurrentLayout = "图纸";
                mPDFExportParams par = new mPDFExportParams();
                par.BackgroundColor = Color.FromArgb(0, Color.White);
                List<string> fileList = new List<string>();
                StreamBuf buf;
                try
                {
                    string filePath = "";
                    string file = GlobleFunc.tempDwgPath;
                    //打开数据库(dwg⽂件)
                    using (Database db = new Database(false, false))//不加参数会出错
                    {

                        db.ReadDwgFile(file, FileOpenMode.OpenForReadAndAllShare, false, "");
                        LayoutTools.PlotDrawingByTK(db, "图纸", "ISO_full_bleed_A3_(420.00_x_297.00_MM)", "monochrome.ctb", "DWG To PDF.pc3", file, out filePath, ref fileList);
                    }
                }
                catch(Teigha.Runtime.Exception ex)
                {

                }
            }
        }

        EditEntitys EditEnt = null;
        bool IsBool = false;
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (toolStripButton3.Checked)
            {
                if (selected.Count > 0)
                {
                    basepanel.Cursor = new System.Windows.Forms.Cursor(Properties.Resources.十字光标.GetHicon());
                    EditEnt = new EditEntitys();
                    EditEnt.TopLevel = false;
                    EditEnt.Dock = DockStyle.Fill;
                    EditEnt.Activate();
                    EditEnt.setEditEntitys(selected, ref database, ref helperDevice);
                    //DBForm.ContextMenuStrip = contextMenu;
                    EditEnt.FormBorderStyle = FormBorderStyle.None;
                    splitContainer1.Panel2Collapsed = false;
                    splitContainer1.Panel2.Controls.Add(EditEnt);
                    splitContainer1.SplitterDistance = splitContainer1.Width - 260;
                    EditEnt.Show();
                    IsBool = true;
                }
                else
                {
                    IsBool = false;
                    splitContainer1.Panel2Collapsed = true;
                    basepanel.Cursor = Cursors.Default;
                    MessageBox.Show("请选择实体对象！", "提示");
                }
            }
            else
            {
                if (EditEnt != null)
                {
                    EditEnt.ClearView();
                    EditEnt.Close();
                    EditEnt = null;
                }
                IsBool = false;
                splitContainer1.Panel2Collapsed = true;
                basepanel.Cursor = Cursors.Default;

            }
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            
            if (database != null)
            {
                using (var trans = database.TransactionManager.StartTransaction())
                {
                    List<Entity> entold = new List<Entity>();
                    ObjectIdCollection oldids = new ObjectIdCollection();
                    ObjectIdCollection newids = new ObjectIdCollection();
                    foreach (ObjectId item in selected)
                    {
                        if (!item.IsErased && item.IsValid)
                            using (Entity ent = (Entity)item.GetObject(OpenMode.ForWrite, false, false))
                            {
                                ent.Erase(true);
                                oldids.Add(ent.Id);
                                newids.Add(new ObjectId());
                                entold.Add((Entity)ent.Clone());

                            }
                    }
                    if (selected.Count > 0)
                    {
                        ReceiverSelection receSelection = new ReceiverSelection(oldids, newids, entold, new List<Entity>(), ref database, ref helperDevice);
                        Invoker.SetCommad(receSelection);
                        selected = new ObjectIdCollection();
                    }
                    trans.Commit();
                }
            }
            if (helperDevice != null)
            {
                helperDevice.Update();
                Invalidate();
            }
        }

        //框选
        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            if (toolStripButton9.Checked)
            {
                OperModel = Operations.SelectFrom;
                basepanel.Cursor = new System.Windows.Forms.Cursor(Properties.Resources.十字光标.GetHicon());
            }
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            if (colorDialog1.ShowDialog() == DialogResult.OK) {
                colorAll = colorDialog1.Color;
                }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            DWF_export(database, helperDevice);
        }

        /// <summary>
        /// 向后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            Invoker.UndoStack();
        }

        /// <summary>
        /// 向前
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            Invoker.RedoStack();
        }

        private void Invoker_ChangeStack()
        {
            toolStripButton8.Text = "撤销(" + Invoker.undoStack.Count.ToString() + ")";
            toolStripButton7.Text = "执行(" + Invoker.redoStack.Count.ToString() + ")";
            if (Invoker.undoStack.Count == 0)
                toolStripButton8.Enabled = false;
            else
                toolStripButton8.Enabled = true;

            if (Invoker.redoStack.Count == 0)
                toolStripButton7.Enabled = false;
            else
                toolStripButton7.Enabled = true;
        }
        #endregion

        #region 界面绘图
        private void DrawPentrack()
        {
            //以为刚开始时，角度和长度可能为o，故用try防止报错
            try
            {
                using (Graphics g = basepanel.CreateGraphics())
                {
                    //设置高质量插值法    
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    //设置高质量,低速度呈现平滑程度    
                    //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
                    //消除锯齿  
                    //g.SmoothingMode = SmoothingMode.AntiAlias;
                    g.PageUnit = GraphicsUnit.Pixel;


                    Pen penMultiLine = new Pen(colorAll, 2); //在每个点上画延长线用的
                                                               //penMultiLine.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
                                                               //penMultiLine.DashPattern = new float[] { 5, 5 };
                    for (int i = 0; i < ListDrwaPen.Count; i++)
                    {
                        g.DrawLines(penMultiLine, ListDrwaPen[i].ToArray());
                    }
                }
            }
            catch { }
        }

        private void DrawArcs()
        {
            //以为刚开始时，角度和长度可能为o，故用try防止报错
            try
            {
                using (Graphics g = basepanel.CreateGraphics())
                {
                    //设置高质量插值法    
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    //设置高质量,低速度呈现平滑程度    
                    //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
                    //消除锯齿  
                    //g.SmoothingMode = SmoothingMode.AntiAlias;
                    g.PageUnit = GraphicsUnit.Pixel;


                    Pen penMultiLine = new Pen(Color.White, 2); //在每个点上画延长线用的
                                                                //penMultiLine.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
                                                                //penMultiLine.DashPattern = new float[] { 5, 5 };

                    double Angle = Function.Angle(MouseDownPt, new Point(MouseDownPt.X + 20, MouseDownPt.Y), MovePoint);
                    double Length = Function.dis(toEyeToWorld(MouseDownPt.X, MouseDownPt.Y), toEyeToWorld(MovePoint.X, MovePoint.Y));
                    g.DrawLine(penMultiLine, MouseDownPt, MovePoint); //画半径线
                    if (MovePoint.Y >= MouseDownPt.Y)
                    {
                        if (!double.TryParse(Angle.ToString(), out Angle) || double.IsNaN(Angle))
                            Angle = 0;
                        _RollAre = (float)(360 - Angle);
                    }
                    else
                    {
                        if (!double.TryParse(Angle.ToString(), out Angle) || double.IsNaN(Angle))
                            Angle = 0;
                        _RollAre = (float)(Angle);
                    }

                    Font FtX = new Font("Arial", 8, FontStyle.Bold); //Ｘ轴的字做小一点
                    Brush FtBrush = new SolidBrush(Color.White); //字体用的笔刷
                    //Rotate_Angle = DouAngle;
                    //显示角度
                    g.DrawString("角度：" + _RollAre.ToString("F3") + "°" + Environment.NewLine + "半径:" + Length.ToString("F3"), FtX, FtBrush, new Point(MovePoint.X + 10, MovePoint.Y));
                    g.Save();
                }
            }
            catch { }
        }

        private void DrawCircle()
        {
            //以为刚开始时，角度和长度可能为o，故用try防止报错
            try
            {
                using (Graphics g = basepanel.CreateGraphics())
                {
                    //设置高质量插值法    
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    //设置高质量,低速度呈现平滑程度    
                    //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
                    //消除锯齿  
                    //g.SmoothingMode = SmoothingMode.AntiAlias;
                    g.PageUnit = GraphicsUnit.Pixel;


                    Pen penMultiLine = new Pen(Color.White, 2); //在每个点上画延长线用的
                                                                //penMultiLine.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom;
                                                                //penMultiLine.DashPattern = new float[] { 5, 5 };

                    double Length = Math.Round(Function.dis(toEyeToWorld(MouseDownPt.X, MouseDownPt.Y), toEyeToWorld(MovePoint.X, MovePoint.Y)), 4);
                    g.DrawLine(penMultiLine, MouseDownPt, MovePoint); //画半径线

                    Font FtX = new Font("Arial", 8, FontStyle.Bold); //Ｘ轴的字做小一点
                    Brush FtBrush = new SolidBrush(Color.White); //字体用的笔刷
                    //Rotate_Angle = DouAngle;
                    //显示角度
                    g.DrawString(" " + Length.ToString(), FtX, FtBrush, new Point(MovePoint.X + 10, MovePoint.Y));
                    g.Save();
                }
            }
            catch { }
        }

        #endregion

        #region 插入实体
        /// <summary>
        /// 是否处于选中状态，禁止界面的缩放
        /// </summary>
        public bool DragSelected = false;

        /// <summary>
        /// 临时存放实体类
        /// </summary>
        public Entity TemporaryEnt = null;

        public EntityType EntType = EntityType.None;

        /// <summary>
        /// 角度值
        /// </summary>
        double _RollAre = 0;

        List<List<Point>> ListDrwaPen = new List<List<Point>>();
        /// <summary>
        /// 画笔
        /// </summary>
        /// <param name="bol"></param>
        public void DrawPebs(bool bol = true)
        {
            if (bol)
            {
                ListDrwaPen = new List<List<Point>>();
                OperModel = Operations.PanelDrawPen;
                basepanel.Cursor = new System.Windows.Forms.Cursor(Properties.Resources.画笔_1_.GetHicon());
            }
            else
            {
                ListDrwaPen = new List<List<Point>>();
                OperModel = Operations.None;
                basepanel.Cursor = Cursors.Default;
                DragSelected = false;
                this.Invalidate();
            }
        }

        /// <summary>
        /// 插入实体
        /// </summary>
        public void InsertLine(bool bol, EntityType _EntType)
        {
            OperModel = bol? Operations.InsertEntity: Operations.None;
            EntType = bol?_EntType : EntityType.None;
            basepanel.Cursor = bol?new System.Windows.Forms.Cursor(Properties.Resources.十字光标.GetHicon()):Cursors.Default;
        }
        
        private void InsertEntityDowm(int X, int Y)
        {
            switch (EntType)
            {
                case EntityType.Line:
                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                    {
                        Line line = new Line(toEyeToWorld(X, Y), toEyeToWorld(X, Y));
                        TemporaryEnt = line;
                        TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                        pView.Add(TemporaryEnt);
                    }
                    break;
                case EntityType.Mline:
                    if (TemporaryEnt != null)
                    {
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                            Mline mine = (Mline)TemporaryEnt;                 
                            Point3d po = mine.VertexAt(mine.NumberOfVertices - 1);
                            mine.RemoveLastSegment(out po);
                            mine.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                            mine.AppendSegment(toEyeToWorld(X, Y));
                            mine.AppendSegment(toEyeToWorld(X, Y));
                         
                        }
                    }
                    else
                    {
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            Mline mine = new Mline();
                            mine.SetDatabaseDefaults(database);
                            mine.Scale = 0;
                            mine.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                            mine.AppendSegment(toEyeToWorld(X, Y));
                            TemporaryEnt = mine;
                            TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                            pView.Add(TemporaryEnt);
                        }
                    }
                    break;
                case EntityType.Arc:
                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                    {
                        Arc arc = new Arc();
                        arc.Center = toEyeToWorld(X, Y);
                        arc.Radius = 0;
                        arc.StartAngle = 0.0;
                        arc.EndAngle = 0.0;
                        TemporaryEnt = arc;
                        TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                        pView.Add(TemporaryEnt);
                    }
                    _RollAre = 0;
                    DrawArcs();
                    break;
                case EntityType.Circle:
                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                    {
                        Circle cir = new Circle();
                        cir.Center = toEyeToWorld(X, Y);
                        cir.Radius = 0;
                        TemporaryEnt = cir;
                        TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                        pView.Add(TemporaryEnt);
                    }
                    break;
                case EntityType.Ellipse:
                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                    {
                        Ellipse ellipse = new Ellipse();
                        ellipse.Center = toEyeToWorld(X, Y);
                        ellipse.RadiusRatio = 0.5;
                        //ellipse.set_StartParam(10);
                        //ellipse.Set(toEyeToWorld(X, Y), new Vector3d(0, 0, 1), new Vector3d(10, 0, 0), 0.5, 0, 0);
                        TemporaryEnt = ellipse;
                        TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                        pView.Add(TemporaryEnt);
                    }
                    break;
                case EntityType.Point:
                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                    {
                        DBPoint Dbmine = new DBPoint();
                        Dbmine.Thickness = 5;
                        Dbmine.Position = toEyeToWorld(X, Y);
                        TemporaryEnt = Dbmine;
                        TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                        pView.Add(TemporaryEnt);
                    }
                    break;
              
                case EntityType.None:
                    break;
                case EntityType.leader:
                    if (TemporaryEnt == null)
                    {
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            Leader pLeader = new Leader();
                            pLeader.SetDatabaseDefaults(database);
                            pLeader.AppendVertex(toEyeToWorld(X, Y));
                            pLeader.AppendVertex(toEyeToWorld(X, Y));
                            TemporaryEnt = pLeader;
                            TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                            pView.Add(TemporaryEnt);
                        }

                    }
                    else
                    {
                        using (var trans = database.TransactionManager.StartTransaction())
                        {
                            using (BlockTableRecord block = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForWrite, false, false))
                            {
                                LayerTable lt = trans.GetObject(database.LayerTableId, OpenMode.ForRead) as LayerTable;
                                string strtext = KryptonInputBox.Show("请输入注释内容！", "提示");
                                if (!string.IsNullOrWhiteSpace(strtext))
                                {
                                    TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                    ObjectId objitem= block.AppendEntity((Entity)TemporaryEnt.Clone());
                                    using (Entity ent=(Entity)objitem.GetObject(OpenMode.ForWrite,false))
                                    {
                                        
                                        Leader Pleader = (Leader)ent;
                                        MText pMText = new MText();
                                        pMText.SetDatabaseDefaults(database);
                                        ObjectId mTextId = block.AppendEntity(pMText);
                                        double textHeight = 0.15;
                                        double textWidth = 1.0;
                                        pMText.Location = Pleader.VertexAt(Pleader.NumVertices-1);
                                        pMText.TextHeight = textHeight;
                                        pMText.Width = textWidth;
                                        pMText.Attachment = AttachmentPoint.MiddleLeft;
                                        pMText.Contents = strtext;
                                        Pleader.Annotation = mTextId;
                                        

                                        List<Entity> entold = new List<Entity>();
                                        List<Entity> newold = new List<Entity>();
                                        ObjectIdCollection oldids = new ObjectIdCollection();
                                        ObjectIdCollection newids = new ObjectIdCollection();
                                        oldids.Add(ObjectId.Null);
                                        oldids.Add(ObjectId.Null);
                                        newids.Add(mTextId);
                                        newids.Add(objitem);
                                        newold.Add((Entity)pMText.Clone());
                                        newold.Add((Entity)Pleader.Clone());

                                        ReceiverSelection receSelection = new ReceiverSelection(oldids, newids, entold, newold, ref database, ref helperDevice);
                                        Invoker.SetCommad(receSelection);
                                    }

                                   
                                }
                                //block.AppendEntity((Entity)TemporaryEnt.Clone());
                            }
                            trans.Commit();
                        }
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            pView.Erase(TemporaryEnt);
                        }
                        TemporaryEnt = null;
                        InsertLine(false, EntityType.None);
                    }
                    break;
                case EntityType.LineDim:
                    if (TemporaryEnt == null)
                    {
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            //AlignedDimension pDimension = new AlignedDimension();
                            //pDimension.SetDatabaseDefaults(database);
                            //pDimension.XLine1Point = toEyeToWorld(X, Y);
                            //pDimension.XLine2Point = toEyeToWorld(MovePoint.X, MovePoint.Y);
                            //pDimension.UsingDefaultTextPosition = true;
                            //TemporaryEnt = pDimension;
                            //pView.Add(TemporaryEnt);
                            Line line = new Line(toEyeToWorld(X, Y), toEyeToWorld(X, Y));
                            TemporaryEnt = line;
                            TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                            pView.Add(TemporaryEnt);
                        }
                    }
                    else
                    {
                        using (var trans = database.TransactionManager.StartTransaction())
                        {
                            using (BlockTableRecord block = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForWrite, false, false))
                            {
                                LayerTable lt = trans.GetObject(database.LayerTableId, OpenMode.ForRead) as LayerTable;
                                //TemporaryEnt.LayerId = lt["H细线"];
                                Line line= (Line)TemporaryEnt;
                                AlignedDimension pDimension = new AlignedDimension();
                                pDimension.SetDatabaseDefaults(database);
                                pDimension.XLine1Point = line.StartPoint;
                                pDimension.XLine2Point = line.EndPoint;
                                //pDimension.UsingDefaultTextPosition = true;
                                pDimension.DimLinePoint = GeTools.MidPoint(line.StartPoint, line.EndPoint).C3D(0,-100);
                                pDimension.LayerId = lt["H标注"];
                                pDimension.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                ObjectId objitem=  block.AppendEntity(pDimension);
                                ReceiverEntity entCommand = new ReceiverEntity(new ObjectId(), objitem, null, (Entity)pDimension.Clone(), ref database, ref helperDevice);
                                Invoker.SetCommad(entCommand);
                            }
                            trans.Commit();
                        }
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            pView.Erase(TemporaryEnt);
                        }
                        TemporaryEnt = null;
                        InsertLine(false, EntityType.None);
                    }
                    break;
                case EntityType.Img:
                    if (TemporaryEnt != null)
                    {
                        using (var trans = database.TransactionManager.StartTransaction())
                        {
                            using (BlockTableRecord block = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForWrite, false, false))
                            {
                                LayerTable lt = trans.GetObject(database.LayerTableId, OpenMode.ForRead) as LayerTable;
                                TemporaryEnt.LayerId = lt["H细线"];
                                ObjectId objitem = block.AppendEntity((Entity)TemporaryEnt.Clone());
                                ReceiverEntity entCommand = new ReceiverEntity(new ObjectId(), objitem, null, (Entity)TemporaryEnt.Clone(), ref database, ref helperDevice);
                                Invoker.SetCommad(entCommand);
                            }
                            trans.Commit();
                        }
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            pView.Erase(TemporaryEnt);
                        }
                        TemporaryEnt = null;
                        OperModel = Operations.None;
                        EntType = EntityType.None;
                        basepanel.Cursor = Cursors.Default;
                    }
                    break;
                case EntityType.ArcLenDim:
                case EntityType.AnglerotaDim:
                case EntityType.AngleLengthDim:
                case EntityType.AngleArcDim:
                case EntityType.ArcDim:
                case EntityType.Dimension:
                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                    {
                        selRect = new RectFram(toEyeToWorld(X, Y));
                        pView.Add(selRect);
                    }
                    break;
                default:
                    break;
            }

        }

        private void InsertEntityMove(int X, int Y)
        {
            if (TemporaryEnt != null || selRect != null)
            {
                switch (EntType)
                {
                    case EntityType.Line:
                    case EntityType.LineDim:
                        Line Linet = (Line)TemporaryEnt;
                        Linet.EndPoint = toEyeToWorld(X, Y);
                        break;
                    case EntityType.Mline:
                        TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                        Mline mine = (Mline)TemporaryEnt;
                        mine.Scale = 0;
                        if (mine.NumberOfVertices <= 1)
                        {
                            mine.AppendSegment(toEyeToWorld(X, Y));
                            mine.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                        }
                        else
                        {
                            Point3d po = mine.VertexAt(mine.NumberOfVertices - 1);
                            mine.RemoveLastSegment(out po);
                            mine.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                            mine.AppendSegment(toEyeToWorld(X, Y));
                           
                        }
                        break;
                    case EntityType.Arc:
                        Arc arc = (Arc)TemporaryEnt;
                        arc.Radius = Function.dis(arc.Center, toEyeToWorld(X, Y));

                        arc.StartAngle = _RollAre * Math.PI / 180;
                        arc.EndAngle = 0.0;


                        break;
                    case EntityType.Circle:
                        Circle cir = (Circle)TemporaryEnt;
                        cir.Radius = Function.dis(cir.Center, toEyeToWorld(X, Y));
                        DrawCircle();
                        break;
                    case EntityType.Point:
                        DBPoint Dbnet = (DBPoint)TemporaryEnt;
                        Dbnet.Position = toEyeToWorld(X, Y);
                        break;
                    case EntityType.Ellipse:
                        Ellipse ellipses = (Ellipse)TemporaryEnt;
                        ellipses.set_StartParam(Function.dis(toEyeToWorld(X, Y), ellipses.Center));
                        ellipses.Set(ellipses.Center, new Vector3d(0, 0, 1), (toEyeToWorld(X, Y) - ellipses.Center), 0.5, 0, 0);
                        break;
                    case EntityType.None:
                        break;
                    case EntityType.Img:
                        RasterImage pImage = (RasterImage)TemporaryEnt;
                        pImage.Orientation = new CoordinateSystem3d(toEyeToWorld(X, Y), new Vector3d(pImage.ImageWidth, 0, 0), new Vector3d(0.0, pImage.ImageHeight, 0));

                        break;
                    case EntityType.leader:
                        if (TemporaryEnt != null)
                        {
                            TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                            Leader leaders = (Leader)TemporaryEnt;
                            if (leaders.NumVertices > 1)
                                leaders.SetVertexAt(leaders.NumVertices - 1, toEyeToWorld(X, Y));
                            else
                                leaders.AppendVertex(toEyeToWorld(X, Y));
                        }
                        break;
                    case EntityType.ArcLenDim:
                    case EntityType.AnglerotaDim:
                    case EntityType.AngleLengthDim:
                    case EntityType.AngleArcDim:
                    case EntityType.ArcDim:
                    case EntityType.Dimension:
                        selRect.setValue(toEyeToWorld(X, Y));
                        break;
                    default:
                        break;
                }
            }
            if (helperDevice != null)
                helperDevice.Update();
            helperDevice.Invalidate();
            Invalidate();
        }

        private void InsertMouseUp(MouseEventArgs e)
        {
            switch (EntType)
            {
                case EntityType.Line:
                case EntityType.Circle:
                case EntityType.Point:
                    if (e.Button == MouseButtons.Left)
                    {
                        using (var trans = database.TransactionManager.StartTransaction())
                        {
                            using (BlockTableRecord block = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForWrite, false, false))
                            {
                                LayerTable lt = trans.GetObject(database.LayerTableId, OpenMode.ForRead) as LayerTable;
                                TemporaryEnt.LayerId = lt["H细线"];
                                //TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                ObjectId Id = block.AppendEntity((Entity)TemporaryEnt.Clone());
                                ReceiverEntity entCommand = new ReceiverEntity(new ObjectId(), Id, null, (Entity)TemporaryEnt.Clone(), ref database, ref helperDevice);
                                Invoker.SetCommad(entCommand);
                            }
                            trans.Commit();
                        }
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            pView.Erase(TemporaryEnt);
                        }
                        TemporaryEnt = null;
                        DragSelected = false;
                        Send_Insert_UC();
                    }
                    break;
                case EntityType.Arc:
                    if (e.Button == MouseButtons.Left)
                    {
                        using (var trans = database.TransactionManager.StartTransaction())
                        {
                            LayerTable lt = trans.GetObject(database.LayerTableId, OpenMode.ForRead) as LayerTable;
                            using (BlockTableRecord block = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForWrite, false, false))
                            {
                                TemporaryEnt.LayerId = lt["H细线"];
                                //TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                ObjectId Id = block.AppendEntity((Entity)TemporaryEnt.Clone());
                           
                                ReceiverEntity entCommand = new ReceiverEntity(new ObjectId(), Id, null, (Entity)TemporaryEnt.Clone(), ref database, ref helperDevice);
                                Invoker.SetCommad(entCommand);
                            }
                            trans.Commit();
                        }
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            pView.Erase(TemporaryEnt);
                        }
                        TemporaryEnt = null;
                        DragSelected = false;
                        Send_Insert_UC();
                    }
                    break;
                case EntityType.Ellipse:
                    if (e.Button == MouseButtons.Left)
                    {
                        using (var trans = database.TransactionManager.StartTransaction())
                        {
                            LayerTable lt = trans.GetObject(database.LayerTableId, OpenMode.ForRead) as LayerTable;
                            using (BlockTableRecord block = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForWrite, false, false))
                            {
                                TemporaryEnt.LayerId = lt["H细线"];
                                //TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                ObjectId Id = block.AppendEntity((Entity)TemporaryEnt.Clone());

                                ReceiverEntity entCommand = new ReceiverEntity(new ObjectId(), Id, null, (Entity)TemporaryEnt.Clone(), ref database, ref helperDevice);
                                Invoker.SetCommad(entCommand);
                            }
                            trans.Commit();
                        }
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            pView.Erase(TemporaryEnt);
                        }
                        TemporaryEnt = null;
                        DragSelected = false;
                        Send_Insert_UC();
                    }
                    break;
                case EntityType.Mline:
                    if (e.Button == MouseButtons.Right)
                    {

                        using (var trans = database.TransactionManager.StartTransaction())
                        {
                            using (BlockTableRecord block = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForWrite, false, false))
                            {
                                LayerTable lt = trans.GetObject(database.LayerTableId, OpenMode.ForRead) as LayerTable;
                                if (TemporaryEnt != null)
                                {
                                    TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                    Mline mine = (Mline)TemporaryEnt;
                                    mine.Scale = 0;
                                    Point3d po = mine.VertexAt(mine.NumberOfVertices - 1);
                                    mine.RemoveLastSegment(out po);
                                    mine.LayerId = lt["H细线"];
                                    mine.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                    ObjectId Id = block.AppendEntity((Entity)TemporaryEnt.Clone());
                                    TemporaryEnt = mine;
                                    TemporaryEnt.LayerId = lt["H细线"];
                                    //TemporaryEnt.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                    ReceiverEntity entCommand = new ReceiverEntity(new ObjectId(), Id, null, (Entity)TemporaryEnt.Clone(), ref database, ref helperDevice);
                                    Invoker.SetCommad(entCommand);

                                    using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                                    {
                                        pView.Erase(TemporaryEnt);
                                        pView.Erase(mine);
                                    }
                                }
                            }
                            trans.Commit();
                        }
                        TemporaryEnt = null;
                        DragSelected = false;
                        Send_Insert_UC();
                    }
                        break;
                case EntityType.None:
                    break;
                case EntityType.Img:
                    break;
                case EntityType.LineDim:
                    break;
                default:
                    if (selRect != null)
                    {
                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                        {
                            ObjectIdCollection objection = new ObjectIdCollection();
                            pView.Select(new Point2dCollection(new Point2d[] { new Point2d(MouseDownPt.X, MouseDownPt.Y), new Point2d(e.X, e.Y) }),
                              new SRnew(objection, database.CurrentSpaceId), MouseDownPt.X < e.X ? Teigha.GraphicsSystem.SelectionMode.Window : Teigha.GraphicsSystem.SelectionMode.Crossing);
                            pView.Erase(selRect);
                            selRect = null;
                            using (var trans = database.TransactionManager.StartTransaction())
                            {
                                List<Entity> entold = new List<Entity>();
                                List<Entity> newold = new List<Entity>();
                                ObjectIdCollection oldids = new ObjectIdCollection();
                                ObjectIdCollection newids = new ObjectIdCollection();
                                LayerTable lt = trans.GetObject(database.LayerTableId, OpenMode.ForRead) as LayerTable;
                                using (BlockTableRecord block = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForWrite, false))
                                    foreach (ObjectId item in objection)
                                    {
                                        using (Entity ent = (Entity)item.GetObject(OpenMode.ForWrite, false))
                                        {
                                            #region ArcLenDim
                                            if (EntType == EntityType.ArcLenDim)
                                            {
                                                if (ent.GetType().Name == "Arc")
                                                    using (Arc pArc = (Arc)ent)
                                                    {
                                                        using (ArcDimension pDimension = new ArcDimension(pArc.Center, pArc.StartPoint, pArc.EndPoint, pArc.Center + new Vector3d(pArc.Radius + 0.45, 0.0, 0.0), "", ObjectId.Null))
                                                        {
                                                            pDimension.SetDatabaseDefaults(database);
                                                           ObjectId id= block.AppendEntity(pDimension);
                                                            pDimension.ArcSymbolType = 1;
                                                            pDimension.UsingDefaultTextPosition = true;
                                                            pDimension.LayerId = lt["H标注"];
                                                            pDimension.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                                            oldids.Add(ObjectId.Null);
                                                            newids.Add(id);
                                                            newold.Add((Entity)pDimension.Clone());
                                                        }
                                                    }
                                            }
                                            #endregion

                                            #region AnglerotaDim
                                            if (EntType == EntityType.AnglerotaDim)
                                            {
                                                if (ent.GetType().Name == "Line")
                                                    using (Line pLine = (Line)ent)
                                                    {
                                                        using (RotatedDimension pDimension = new RotatedDimension(0, pLine.StartPoint,
                                                        pLine.EndPoint, new Point3d((pLine.StartPoint.X + pLine.EndPoint.X) / 2, pLine.StartPoint.Y, 0), String.Format("倾斜注释:" + Function.Angle(pLine.StartPoint, new Point3d(pLine.StartPoint.X + 10, pLine.StartPoint.Y, 0), pLine.EndPoint) + "°"), ObjectId.Null))
                                                        {
                                                            pDimension.SetDatabaseDefaults(database);
                                                            ObjectId id= block.AppendEntity(pDimension);
                                                            pDimension.UsingDefaultTextPosition = true;
                                                            pDimension.LayerId = lt["H标注"];
                                                            pDimension.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                                            oldids.Add(ObjectId.Null);
                                                            newids.Add(id);
                                                            newold.Add((Entity)pDimension.Clone());
                                                        }
                                                    }
                                            }
                                            #endregion

                                            #region AngleArcDim
                                            if (EntType == EntityType.AngleArcDim)
                                            {
                                                if (ent.GetType().Name == "Arc")
                                                    using (Arc pArc = (Arc)ent)
                                                    {
                                                        using (Point3AngularDimension pDimension = new Point3AngularDimension())
                                                        {
                                                            pDimension.SetDatabaseDefaults(database);
                                                            ObjectId id=  block.AppendEntity(pDimension);
                                                            pDimension.CenterPoint = pArc.Center;
                                                            pDimension.ArcPoint = pArc.Center + new Vector3d(pArc.Radius + 0.45, 0.0, 0.0);
                                                            pDimension.XLine1Point = pArc.StartPoint;
                                                            pDimension.XLine2Point = pArc.EndPoint;
                                                            pDimension.UsingDefaultTextPosition = true;
                                                            pDimension.LayerId = lt["H标注"];
                                                            pDimension.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                                            oldids.Add(ObjectId.Null);
                                                            newids.Add(id);
                                                            newold.Add((Entity)pDimension.Clone());
                                                        }
                                                    }
                                            }
                                            #endregion

                                            #region ArcDim
                                            if (EntType == EntityType.ArcDim)
                                            {
                                                if (ent.GetType().Name == "Arc")
                                                    using (Arc pArc = (Arc)ent)
                                                    {
                                                        using (RadialDimensionLarge pDimension = new RadialDimensionLarge())
                                                        {
                                                            ObjectId id = block.AppendEntity(pDimension);

                                                            pDimension.SetDatabaseDefaults(database);

                                                            Point3d centerPoint, chordPoint, overrideCenter, jogPoint, textPosition;

                                                            centerPoint = pArc.Center;
                                                            chordPoint = centerPoint + new Vector3d(pArc.Radius, 0.0, 0.0).RotateBy(0.5 * (pArc.StartAngle + pArc.EndAngle), Vector3d.ZAxis);

                                                            overrideCenter = centerPoint + new Vector3d(pArc.Radius * 3.0 / 8.0, 0.0, 0.0);

                                                            jogPoint = overrideCenter + 0.5 * (chordPoint - overrideCenter);

                                                            textPosition = centerPoint + 0.7 * (chordPoint - centerPoint);

                                                            double jogAngle = 45 * Math.PI / 180; ;

                                                            pDimension.Center = centerPoint;
                                                            pDimension.ChordPoint = pArc.Center + new Vector3d(pArc.Radius, 0.0, 0.0).RotateBy(0.5 * (pArc.StartAngle + pArc.EndAngle), Vector3d.ZAxis);
                                                            pDimension.OverrideCenter = overrideCenter;
                                                            pDimension.JogPoint = jogPoint;
                                                            pDimension.TextPosition = textPosition;
                                                            pDimension.JogAngle = jogAngle;
                                                            pDimension.UsingDefaultTextPosition = true;
                                                            pDimension.LayerId = lt["H标注"];
                                                            pDimension.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                                            oldids.Add(ObjectId.Null);
                                                            newids.Add(id);
                                                            newold.Add((Entity)pDimension.Clone());
                                                        }
                                                    }
                                            }
                                            #endregion

                                            #region Dimension
                                            if (EntType == EntityType.Dimension)
                                            {
                                                if (ent.GetType().Name == "Arc")
                                                {
                                                    Arc pArc = (Arc)ent;
                                                    using (ArcDimension pDimension = new ArcDimension(pArc.Center, pArc.StartPoint, pArc.EndPoint, pArc.Center + new Vector3d(pArc.Radius + 0.45, 0.0, 0.0), "", ObjectId.Null))
                                                    {
                                                        pDimension.SetDatabaseDefaults(database);
                                                        ObjectId id= block.AppendEntity(pDimension);
                                                        pDimension.UsingDefaultTextPosition = true;
                                                        pDimension.ArcSymbolType = 1;
                                                        pDimension.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                                        pDimension.LayerId = lt["H标注"];
                                                        oldids.Add(ObjectId.Null);
                                                        newids.Add(id);
                                                        newold.Add((Entity)pDimension.Clone());
                                                    }
                                                }
                                                else if (ent.GetType().Name == "Line")
                                                {
                                                    Line line = (Line)ent;
                                                    AlignedDimension pDimension = new AlignedDimension();
                                                    pDimension.SetDatabaseDefaults(database);
                                                    pDimension.XLine1Point = line.StartPoint;
                                                    pDimension.XLine2Point = line.EndPoint;
                                                    pDimension.UsingDefaultTextPosition = true;
                                                    pDimension.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                                    pDimension.LayerId = lt["H标注"];
                                                    ObjectId id= block.AppendEntity(pDimension);

                                                    oldids.Add(ObjectId.Null);
                                                    newids.Add(id);
                                                    newold.Add((Entity)pDimension.Clone());
                                                }
                                                else if (ent.GetType().Name == "Polyline")
                                                {
                                                    Teigha.DatabaseServices.Polyline line = (Teigha.DatabaseServices.Polyline)ent;
                                                    for (int i = 0; i < line.NumberOfVertices; i++)
                                                    {
                                                        switch (line.GetSegmentType(i))
                                                        {
                                                            case SegmentType.Empty:
                                                                break;
                                                            case SegmentType.Point:
                                                                break;
                                                            case SegmentType.Arc:
                                                                CircularArc3d pArc = line.GetArcSegmentAt(i);
                                                                using (ArcDimension pDimension = new ArcDimension(pArc.Center, new Point3d(pArc.StartPoint.X, pArc.StartPoint.Y, 0), new Point3d(pArc.EndPoint.X, pArc.EndPoint.Y, 0), pArc.Center + new Vector3d(pArc.Radius + 0.45, 0.0, 0.0), "", ObjectId.Null))
                                                                {
                                                                    pDimension.SetDatabaseDefaults(database);
                                                                    ObjectId idw= block.AppendEntity(pDimension);
                                                                    pDimension.ArcSymbolType = 1;
                                                                    pDimension.UsingDefaultTextPosition = true;
                                                                    pDimension.LayerId = lt["H标注"];
                                                                    oldids.Add(ObjectId.Null);
                                                                    newids.Add(idw);
                                                                    newold.Add((Entity)pDimension.Clone());
                                                                }
                                                                break;
                                                            case SegmentType.Coincident:
                                                                break;
                                                            case SegmentType.Line:
                                                                LineSegment3d lines = line.GetLineSegmentAt(i);
                                                                AlignedDimension pDimension2 = new AlignedDimension();
                                                                pDimension2.SetDatabaseDefaults(database);
                                                                pDimension2.XLine1Point = lines.StartPoint;
                                                                pDimension2.XLine2Point = lines.EndPoint;
                                                                pDimension2.UsingDefaultTextPosition = true;
                                                                pDimension2.Color = Teigha.Colors.Color.FromRgb(colorAll.R, colorAll.G, colorAll.B);
                                                                pDimension2.LayerId = lt["H标注"];
                                                                ObjectId id= block.AppendEntity(pDimension2);

                                                                oldids.Add(ObjectId.Null);
                                                                newids.Add(id);
                                                                newold.Add((Entity)pDimension2.Clone());
                                                                break;
                                                            default:
                                                                break;
                                                        }
                                                    }
                                                }

                                            }
                                            #endregion
                                        }
                                    }

                                if (objection.Count > 0)
                                {
                                    ReceiverSelection receSelection = new ReceiverSelection(oldids, newids, entold, newold, ref database, ref helperDevice);
                                    Invoker.SetCommad(receSelection);
                                }
                                trans.Commit();
                            }
                        }
                        DragSelected = false;
                        InsertLine(false, EntityType.None);
                    }
                    break;
            }
           
            if (helperDevice != null)
                helperDevice.Update();
            helperDevice.Invalidate();
            Invalidate();
        }
        
        /// <summary>
        /// 启动拖拽界面
        /// </summary>
        public void SetmouseTypeOk(bool bol = true)
        {
            if (bol)
            {
                basepanel.Cursor = new System.Windows.Forms.Cursor(Properties.Resources.拖拽32白色.GetHicon());
                OperModel = Operations.Drag;
            }
            else
            {
                basepanel.Cursor = Cursors.Default;
                DragSelected = false;
                OperModel = Operations.None;
            }
        }

        /// <summary>
        /// 插入dwf
        /// </summary>
        public void InsertDwfBy()
        {
            OpenFileDialog saveDialog = new OpenFileDialog();
            saveDialog.Filter = String.Format("DWF (Desgin Web Format) (*.dwf)|*.dwf");
            if (DialogResult.OK == saveDialog.ShowDialog())
            {
                SystemObjects.DynamicLinker.LoadApp("TD_Dwf7Import", false, false);
                using (DWFImport dwfimp = new DWFImport())
                {
                    using (Dictionary props = dwfimp.Properties)
                    {
                        if (props.Contains("Database"))
                            props.AtPut("Database", database);
                        if (props.Contains("DwfPath")) // Check if property is supported
                            props.AtPut("DwfPath", new RxVariant(saveDialog.FileName));
                        if (props.Contains("Password")) // Check if property is supported
                            props.AtPut("Password", new RxVariant(String.Format("")));
                        if (props.Contains("PaperWidth")) // Check if property is supported
                            props.AtPut("PaperWidth", new RxVariant(297.0));
                        if (props.Contains("PaperHeight")) // Check if property is supported
                            props.AtPut("PaperHeight", new RxVariant(210.0));
                        if (props.Contains("PreserveColorIndices")) // Check if property is supported
                            props.AtPut("PreserveColorIndices", new RxVariant(true));
                        if (props.Contains("LayoutNumber")) // Check if property is supported
                            props.AtPut("LayoutNumber", new RxVariant(-1));
                        if (props.Contains("ImportW3d")) // Check if property is supported
                            props.AtPut("ImportW3d", new RxVariant(true));
                    }
                    dwfimp.Import();
                }
            }
        }

        /// <summary>
        /// 插入图片
        /// </summary>
        public void InsertImages()
        {
            OpenFileDialog saveDialog = new OpenFileDialog();
            saveDialog.Filter = String.Format("img (*.jpg)|*.jpg");
            if (DialogResult.OK == saveDialog.ShowDialog())
            {
                string path = Path.GetDirectoryName(saveDialog.FileName);
                string Imgpath = Path.Combine(Path.GetDirectoryName(DwgPath), Path.GetFileName(saveDialog.FileName));
                if (Path.GetDirectoryName(DwgPath) != path)
                    File.Copy(saveDialog.FileName, Imgpath, true);

                System.Drawing.Image imgs = System.Drawing.Image.FromFile(saveDialog.FileName);
                int w = imgs.Width;
                int h = imgs.Height;
                imgs.Dispose();
                using (var trans = database.TransactionManager.StartTransaction())
                {
                    try
                    {
                        using (BlockTableRecord bBTR = (BlockTableRecord)database.CurrentSpaceId.GetObject(OpenMode.ForWrite))
                        {
                            ObjectId imageDictId = RasterImageDef.CreateImageDictionary(bBTR.Database);
                            using (DBDictionary pImageDict = (DBDictionary)imageDictId.GetObject(OpenMode.ForWrite))
                            {

                                /**********************************************************************/
                                /* Create an ImageDef object                                          */
                                /**********************************************************************/
                                using (RasterImageDef pImageDef = new RasterImageDef())
                                {
                                    ObjectId imageDefId = pImageDict.SetAt("timg", pImageDef);

                                    /**********************************************************************/
                                    /* Set some parameters                                                */
                                    /**********************************************************************/
                                    pImageDef.SourceFileName = String.Format("timg.jpg");

                                    using (GIRasterImageDesc img = new GIRasterImageDesc((uint)w, (uint)h, Units.Inch))
                                    {
                                        pImageDef.SetImage(img.UnmanagedObject, (IntPtr)0, true);

                                        /**********************************************************************/
                                        /* Create an Image object                                             */
                                        /**********************************************************************/
                                        //using (RasterImage pImage = new RasterImage())
                                        //{
                                        //    pImage.SetDatabaseDefaults(bBTR.Database);
                                        //    bBTR.AppendEntity(pImage);
                                        //    pImage.ShowImage = true;
                                        //    /**********************************************************************/
                                        //    /* Set some parameters                                                */
                                        //    /**********************************************************************/
                                        //    pImage.ImageDefId = imageDefId;
                                        //    pImage.Orientation = new CoordinateSystem3d(toEyeToWorld(MouseDownPt.X, MouseDownPt.Y), new Vector3d(w, 0, 0), new Vector3d(0.0, h, 0));
                                        //    pImage.DisplayOptions = ImageDisplayOptions.Show | ImageDisplayOptions.ShowUnaligned;

                                        //}

                                        using (Teigha.GraphicsSystem.View pView = helperDevice.ActiveView)
                                        {
                                            RasterImage pImage = new RasterImage();
                                            pImage.SetDatabaseDefaults(bBTR.Database);
                                            pView.Add(pImage);
                                            pImage.ShowImage = true;
                                            /**********************************************************************/
                                            /* Set some parameters                                                */
                                            /**********************************************************************/
                                            pImage.ImageDefId = imageDefId;
                                            pImage.Orientation = new CoordinateSystem3d(toEyeToWorld(MouseDownPt.X, MouseDownPt.Y), new Vector3d(w, 0, 0), new Vector3d(0.0, h, 0));
                                            pImage.DisplayOptions = ImageDisplayOptions.Show | ImageDisplayOptions.ShowUnaligned;

                                            TemporaryEnt = pImage;
                                        }
                                    }

                                }
                            }
                        }

                        OperModel = Operations.InsertEntity;
                        EntType = EntityType.Img;
                        basepanel.Cursor = new System.Windows.Forms.Cursor(Properties.Resources.十字光标.GetHicon());
                        trans.Commit();
                    }
                    catch (System.Exception ex)
                    {
                        trans.Abort();
                        OperModel = Operations.None;
                        EntType = EntityType.None;
                        basepanel.Cursor = Cursors.Default;
                        KryptonMessageBox.Show("插入图片失败！错误原因：" + ex.Message);
                    }
                }
            }
            else
            {
                OperModel =  Operations.None ;
                EntType =  EntityType.None;
                basepanel.Cursor =  Cursors.Default;
            }
            if (helperDevice != null)
                helperDevice.Update();
            helperDevice.Invalidate();
            Invalidate();
        }
        
        private void 打开文件所在位置ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(System.IO.Path.GetDirectoryName(DwgPath)))
            {
                KryptonMessageBox.Show("项目路径【" + System.IO.Path.GetDirectoryName(DwgPath) + "】不存在！");
                return;
            }
            System.Diagnostics.Process open = new System.Diagnostics.Process();
            open.StartInfo.FileName = "explorer";
            open.StartInfo.Arguments = @"/select," + DwgPath;
            open.Start();
        }

        /// <summary>
        /// 添加实体备注
        /// </summary>
        public void AddEntity_Xdata(string StrText)
        {
            using (var trans = database.TransactionManager.StartTransaction())
            {
                using (RegAppTable appTbl = trans.GetObject(database.RegAppTableId, OpenMode.ForWrite) as RegAppTable)
                    if (!appTbl.Has(Application.ProductName))
                    {
                        RegAppTableRecord appTblRcd = new RegAppTableRecord();
                        appTblRcd.Name = Application.ProductName;
                        appTbl.Add(appTblRcd);
                        trans.AddNewlyCreatedDBObject(appTblRcd, true);
                    }
                
                if (selected.Count > 0)
                {
                    foreach (ObjectId item in selected)
                    {
                        using (Entity ent = (Entity)item.GetObject(OpenMode.ForWrite,false))
                        {
                            ResultBuffer resBuf = ent.XData;
                            if (resBuf != null)
                            {
                                resBuf.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, StrText));
                                ent.XData = resBuf;
                            }
                            else
                            {
                                ResultBuffer resBufNEw = new ResultBuffer();
                                resBufNEw.Add(new TypedValue((int)DxfCode.ExtendedDataRegAppName, Application.ProductName));
                                resBufNEw.Add(new TypedValue((int)DxfCode.ExtendedDataAsciiString, StrText));
                                ent.XData = resBufNEw;
                            }
                        }
                    }
                }
                trans.Commit();
            }
        }
        #endregion

        #region 布局变化委托重新加载
        public delegate void Send_Change_Layout_To_Form_Main(string layoutName);
        public event Send_Change_Layout_To_Form_Main Send_Change_Layout;
        #endregion

        #region 保存临时模板
        public void CheckDictionary(string dic)
        {         
            if (!Directory.Exists(dic))
            {
                Directory.CreateDirectory(dic);
            }       
        }

        public  void SaveTempDwg(string dicName, string name)
        {
            try
            {
                string dic = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "TuZhi\\";
                string dicPath = dic + dicName + "\\";
                CheckDictionary(dicPath);
                string path = dicPath + name + ".dwg";
                if (database != null)
                {
                    database.Save();
                    database.SaveActiveDrawing(dicPath, name);
                    System.Threading.Thread.Sleep(1000);
                    if (!FileSecurity.IsOccupied(path))
                    {
                        //_parent.Load_the_dwgordxf(path, false);
                        _parent.loadDwgFiles(path);
                    }
                }
            }
            catch (System.Exception ex)
            {

            }
          
        }

        public void SaveCADFiles(string folder, string name)
        {
            try
            {
               
                string dicPath = folder + "\\";
                CheckDictionary(dicPath);
                string path = dicPath + name + ".dwg";
                if (database != null)
                {
                    database.Save();
                    database.SaveActiveDrawing(dicPath, name);
                    System.Threading.Thread.Sleep(1000);
                    if (!FileSecurity.IsOccupied(path))
                    {
                        //_parent.Load_the_dwgordxf(path, false);
                        _parent.loadDwgFiles(path);
                    }
                }
            }
            catch (System.Exception ex)
            {

            }

        }

        //public void Dispose()
        //{
        //    GC.SuppressFinalize(this);
        //}
        async Task PutTaskDelay(int time=10)
        {
            await Task.Delay(time);
        }

        #endregion 
        public void Test()
        {
            Database db = HostApplicationServices.WorkingDatabase;
            

            InitConfig.InitLayer();
            InitConfig.InitTextStyle("SRB.HT", "仿宋", 0.7);

            InitConfig.InitDimStyle(Unit.Millimeter, Unit.Centimeter, 10, Extensions.curFont);
            InitConfig.InitDimStyle(Unit.Millimeter, Unit.Centimeter, 20, Extensions.curFont);
            InitConfig.InitDimStyle(Unit.Millimeter, Unit.Millimeter, 20, Extensions.curFont);
            InitConfig.InitDimStyle(Unit.Millimeter, Unit.Millimeter, 1, Extensions.curFont);
            InitConfig.InitBlock();

            Point2d p1 = new Point2d(0, 0);
            Point2d p2 = new Point2d(125, 0);
            Point2d p3 = new Point2d(125, 200);
            Point2d p4 = new Point2d(0, 210);
            Point2d p5 = new Point2d(-50, 0);
            Extents2d ext = new Extents2d(p1,p1);
            DimPloter.DimRot(db,p1.C3D(), p2.C3D(), p4.C3D(), ref ext, 0, 20);
            DimPloter.DimAli(db,p1.C3D(200, 100), p2.C3D(500, 100), p4.C3D(0, 100), ref ext, 20);
            DimPloter.DimAli(db,p1.C3D(200, 100), p2.C3D(500, 100), p4.C3D(0, 200), ref ext, 20,"",Unit.Millimeter, Unit.Centimeter);

            DimPloter.DimRot(db,p1.C3D(0, 100), p2.C3D(0, 100), p4.C3D(0, -100), ref ext, 0, 1);
            DimPloter.DimAli(db,p1.C3D(200, 100), p2.C3D(500, 200), p4.C3D(0, -200), ref ext, 1);
            TextPloter.AddTitle(db,Point2d.Origin.C2D(-100, 50), ref ext, "断面图", "");

            DimPloter.AddBG(db,100, p5.C3D(), ref ext, 8);

            DimPloter.AddArrowTitle(db,Point2d.Origin.C3D(-300, 150), "断面图", ref ext, 2.5, 1);

            DimPloter.AddArrowTitle(db,Point2d.Origin.C3D(-500, 150), "断面图", ref ext, 2.5, 1, true);

            DimPloter.AddCirText(db,"P2", Point2d.Origin.C2D(-100, -50), ref ext, 1, "SRB.HT", 90, 2.5, 3);

            PLPloter.AddArcPoly(db,p1.C2D(0,-20), ref ext, 1000, 1000, "H虚线", 200);

            LayoutTools.CreateLayout( "布局1", ext, 30, 10, 25, 10, 100, false);
            //SaveTempDwg();
        }

        public void SelectDrawingSubstructure(SubstructureType type, ref DataRow row, ref double selectScale,ref bool isDawing)
        {
            SelectInfoForm frm;
            switch (type)
            {
                case SubstructureType.PileCap:
                    frm = new SelectInfoForm("pileCap");
                    frm.ShowDialog();
                    if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
                    {
                        PileCapParameter para = ModelOper.GetPileCapPara(frm.para.Id, out row);
                        selectScale= frm.para.Scale;
                        isDawing = true;
                    }
                    else
                    {
                        isDawing = false;
                    }
                    break;
                case SubstructureType.Pile:
                    frm = new SelectInfoForm("pile");
                    frm.ShowDialog();
                    if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
                    {
                        PileParameter para = ModelOper.GetPilePara(frm.para.Id, out row);
                        selectScale = frm.para.Scale;
                        isDawing = true;
                    }
                    else
                    {
                        isDawing = false;
                    }
                    break;
                case SubstructureType.Plinth:
                    frm = new SelectInfoForm("Plinth");
                    frm.ShowDialog();
                    if (frm.DialogResult == System.Windows.Forms.DialogResult.OK)
                    {
                        PlinthParameter para = ModelOper.GetPlinthPara(frm.para.Id, out row);
                        selectScale = frm.para.Scale;
                        isDawing = true;
                    }
                    else
                    {
                        isDawing = false;
                    }
                    break;
            }
            //SaveTempDwg();
        }
        public void DrawingSubstructure(SubstructureType type, DataRow row, double selectScale)
        {
            switch (type)
            {
                case SubstructureType.PileCap:
                    new Substructure().DrawingPileCap( row,selectScale);
                    SaveTempDwg("PileCap", "PileCap" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                    break;
                case SubstructureType.Pile:
                    new Substructure().DrawingPile(row,selectScale);
                    SaveTempDwg("Pile","Pile" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                 
                    break;
                case SubstructureType.Plinth:
                    new Substructure().DrawingPlinth(row,selectScale);
                    SaveTempDwg("Plinth","Plinth" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                    break;
            }
        }

        public void DrawingSubstructureNew(SubstructureType type, DataRow row, double selectScale)
        {
            switch (type)
            {
                case SubstructureType.PileCap:
                    new SubStructureDrawing().DrawingPileCap(row, selectScale);
                    SaveTempDwg("PileCap", "PileCap" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                    break;
                case SubstructureType.Pile:
                    new SubStructureDrawing().DrawingPile(row, selectScale);
                    SaveTempDwg("Pile", "Pile" + DateTime.Now.ToString("yyyyMMddHHmmss"));

                    break;
                case SubstructureType.Plinth:
                    new Substructure().DrawingPlinth(row, selectScale);
                    SaveTempDwg("Plinth", "Plinth" + DateTime.Now.ToString("yyyyMMddHHmmss"));
                    break;
            }
        }

        public void DrawingPierSubstructure(string paraFile, string saveFolder, PierSubstructureType type)
        {

            new PierSubstructureDrawing().DrawingPier(database,paraFile, 15, type);
            SaveCADFiles(saveFolder, "PierSubstructure" + DateTime.Now.ToString("yyyyMMddHHmmss"));

        }
        private void TeighaBase_FormClosed(object sender, FormClosedEventArgs e)
        {
            //注销Id号为100的热键设定
            HotKeysManager.UnregisterHotKey(Handle, 100);
            //注销Id号为101的热键设定
            HotKeysManager.UnregisterHotKey(Handle, 101);
            HotKeysManager.UnregisterHotKey(Handle, 102);
        }

        private void basepanel_MouseEnter(object sender, EventArgs e)
        {
            HotKeysManager.RegisterHotKey(Handle, 100, HotKeysManager.KeyModifiers.Ctrl, Keys.C);
            HotKeysManager.RegisterHotKey(Handle, 101, HotKeysManager.KeyModifiers.Ctrl, Keys.V);
            HotKeysManager.RegisterHotKey(Handle, 102, HotKeysManager.KeyModifiers.Ctrl, Keys.A);
        }

        private void basepanel_MouseLeave(object sender, EventArgs e)
        {

            //注销Id号为100的热键设定
            HotKeysManager.UnregisterHotKey(Handle, 100);
            //注销Id号为101的热键设定
            HotKeysManager.UnregisterHotKey(Handle, 101);
            HotKeysManager.UnregisterHotKey(Handle, 102);
        }
    }
}
